package com.brogent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.brogent.util.PngFilter;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SelectFile extends ListActivity {
    private List<String> items     = null;
    private List<String> paths     = null;
    private final String ROOT_PATH = "/";
    private TextView     mPath;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.select);
        mPath = (TextView) findViewById(R.id.mPath);

        getFileDir(ROOT_PATH);
    }

    private void getFileDir(String filePath) {
        mPath.setText(filePath);

        items = new ArrayList<String>();
        paths = new ArrayList<String>();
        File f = new File(filePath);
        File[] files = f.listFiles(new PngFilter());

        if (!filePath.equals(ROOT_PATH)) {
            items.add("Back to " + ROOT_PATH);
            paths.add(ROOT_PATH);
            items.add("Back to ../");
            paths.add(f.getParent());
        }

        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            items.add(file.getName());
            paths.add(file.getPath());
        }

        ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.file_row, items);
        setListAdapter(fileList);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        File file = new File(paths.get(position));

        if (file.isDirectory()) {
            getFileDir(paths.get(position));
        } else {
            Intent intent = this.getIntent();
            Bundle bundle = new Bundle();
            bundle.putString("path", file.getAbsolutePath());
            intent.putExtras(bundle);
            SelectFile.this.setResult(RESULT_OK, intent);

            SelectFile.this.finish();
        }
    }
}
